document.addEventListener('DOMContentLoaded', () => {
    const searchForm = document.querySelector('.search-form');
    const searchInput = document.querySelector('#search-input');
    const searchBtn = document.querySelector('#search-btn');
    const resultsTable = document.querySelector('#results-table');
    const tableBody = document.querySelector('#table-body');
    const tableHead = document.querySelector('#table-head');
    const loadingIndicator = document.querySelector('#loading');
    const errorMessage = document.querySelector('#error');
    const searchMessage = document.querySelector('#search-message');

    // Handle search form submission
    searchForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const query = searchInput.value.trim();
        
        if (!query) {
            errorMessage.textContent = 'Please enter a search term';
            errorMessage.style.display = 'block';
            return;
        }

        try {
            // Show loading state
            loadingIndicator.style.display = 'block';
            errorMessage.style.display = 'none';
            resultsTable.style.display = 'none';
            searchMessage.textContent = 'Searching...';

            // Make API call to search endpoint
            const response = await fetch(`/api/search?query=${encodeURIComponent(query)}`);
            
            if (!response.ok) {
                throw new Error('Search failed. Please try again.');
            }

            const results = await response.json();
            
            // Display results
            if (!Array.isArray(results) || results.length === 0) {
                searchMessage.textContent = 'No results found';
                resultsTable.style.display = 'none';
            } else {
                displayResults(results);
                searchMessage.textContent = `Found ${results.length} results`;
                resultsTable.style.display = 'table';
            }

        } catch (error) {
            errorMessage.textContent = error.message;
            errorMessage.style.display = 'block';
            resultsTable.style.display = 'none';
            searchMessage.textContent = 'Search failed';
        } finally {
            loadingIndicator.style.display = 'none';
        }
    });

    // Display search results in table
    function displayResults(results) {
        if (!Array.isArray(results) || results.length === 0) {
            return;
        }

        // Clear previous results
        tableHead.innerHTML = '';
        tableBody.innerHTML = '';

        // Create table headers
        const headerRow = document.createElement('tr');
        const headers = Object.keys(results[0] || {});
        
        headers.forEach(header => {
            const th = document.createElement('th');
            th.textContent = header.charAt(0).toUpperCase() + header.slice(1); // Capitalize first letter
            headerRow.appendChild(th);
        });
        
        tableHead.appendChild(headerRow);

        // Create table rows
        results.forEach(result => {
            if (!result) return; // Skip if result is null or undefined
            
            const row = document.createElement('tr');
            
            headers.forEach(header => {
                const cell = document.createElement('td');
                if (header === 'id' || header === 'ISBN') {
                    const link = document.createElement('a');
                    link.href = `/detail.html?id=${result[header]}`;
                    link.textContent = result[header];
                    cell.appendChild(link);
                } else {
                    cell.textContent = result[header] || '';
                }
                row.appendChild(cell);
            });
            
            tableBody.appendChild(row);
        });
    }

    // Check if there's a query parameter and perform search
    const urlParams = new URLSearchParams(window.location.search);
    const initialQuery = urlParams.get('query');
    if (initialQuery) {
        searchInput.value = initialQuery;
        searchForm.dispatchEvent(new Event('submit'));
    }
});
